package dao;

import model.Player;
import type.GameMode;

import java.sql.*;
import java.util.AbstractMap;
import java.util.ArrayList;
import java.util.Map;
import java.util.TreeSet;

public class DatabaseConnection {
        public static final String url = "jdbc:mysql://localhost:3306/greedysnake?useUnicode=true&characterEncoding=utf-8&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=GMT%2B8";
        public static final String username = "root";
        public static final String password = "123456";
        public static int model;
        public static void addPlayer(Player player, GameMode model1) {
            if (model1==GameMode.CLASSIC) model=1;
            else model=2;
        try (Connection connection = DriverManager.getConnection(url,username,password)) {
            String sql = "INSERT INTO rankinglist (name, score,model) VALUES (?, ?, ?)";
            PreparedStatement statement = connection.prepareStatement(sql);
            statement.setString(1, player.getName());
            statement.setInt(2, player.getScore());
            statement.setInt(3,model);
            statement.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public static ArrayList<Player> findPlayers(int model) {
        ArrayList<Player> players = new ArrayList<Player>();
        try (Connection connection = DriverManager.getConnection(url, username, password)) {
            String sql = "SELECT name, score  FROM rankinglist WHERE model = ?  ORDER BY score DESC";
            PreparedStatement statement = connection.prepareStatement(sql);
            statement.setInt(1,model);
            ResultSet resultSet = statement.executeQuery();

            // 取前十条数据，将name和score值存入
                while (resultSet.next()) {
                    String name = resultSet.getString("name");
                    int score = resultSet.getInt("score");
                    players.add(new Player(name, score));
                    if(players.size()==10){
                        break;
                    }
                }
        } catch (SQLException e) {
            e.printStackTrace();
            return null;
        }
        return  players;
    }


}

